package pfq.demo.rx;

import android.os.Bundle;
import android.view.View;
import android.widget.TextView;

import androidx.appcompat.app.AppCompatActivity;
import io.reactivex.Observable;
import io.reactivex.ObservableEmitter;
import io.reactivex.ObservableOnSubscribe;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.disposables.CompositeDisposable;
import io.reactivex.observers.DisposableObserver;
import io.reactivex.schedulers.Schedulers;
import pfq.demo.R;

/**
 * 演示了使用RxJava在子线程执行耗时操作，并实时更新UI
 */
public class UIUpdateActivity extends AppCompatActivity {

    private TextView mStatusTextView;

    private CompositeDisposable compositeDisposable = new CompositeDisposable();

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_rx_ui);

        findViewById(R.id.startDownloadButton).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                startDownload();
            }
        });

        mStatusTextView = (TextView) findViewById(R.id.statusTextView);

    }

    private void startDownload() {

        // 被观察者：执行耗时操作
        final Observable<Integer> observable = Observable.create(new ObservableOnSubscribe<Integer>() {
            @Override
            public void subscribe(ObservableEmitter<Integer> e) throws Exception {
                for (int i = 0; i < 3; i++) {
                    Thread.sleep(1000);
                    e.onNext(i);
                }
                e.onComplete();
            }
        });

        // 观察者：UI
        DisposableObserver<Integer> disposableObserver = new DisposableObserver<Integer>() {
            @Override
            public void onNext(Integer integer) {
                mStatusTextView.setText("当前下载进度：" + (int) ((integer + 1) / 3.0 * 100) + "%");
            }

            @Override
            public void onError(Throwable e) {

            }

            @Override
            public void onComplete() {
                mStatusTextView.setText("下载完成");
            }
        };
        observable.subscribeOn(Schedulers.io()).observeOn(AndroidSchedulers.mainThread()).subscribe(disposableObserver);
        compositeDisposable.add(disposableObserver);


    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        compositeDisposable.clear();
    }
}
